<template>
  <div class="stock-out-detail">
    <el-page-header @back="goBack" title="出库单详情">
      <template #content>
        <span class="page-header-title">出库单详情</span>
      </template>
    </el-page-header>
    
    <div class="page-content" v-loading="loading">
      <template v-if="!loading && stockOut">
        <!-- 状态横幅 -->
        <div class="status-banner" :class="getStatusClass(stockOut.status)">
          <el-icon :size="24" class="status-icon">
            <component :is="getStatusIcon(stockOut.status)"></component>
          </el-icon>
          <div class="status-info">
            <h3>{{ getStatusText(stockOut.status) }}</h3>
            <p>出库单号: {{ stockOut.orderNumber }}</p>
          </div>
          <div class="banner-actions" v-if="stockOut.status === 0">
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit"
              v-permission="'inventory.stockOut.edit'"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleConfirm"
              v-permission="'inventory.stockOut.confirm'"
            >
              确认出库
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleCancel"
              v-permission="'inventory.stockOut.cancel'"
            >
              作废
            </el-button>
          </div>
          <div class="banner-actions" v-else>
            <el-button type="primary" size="small" @click="handlePrint">
              打印
            </el-button>
          </div>
        </div>
        
        <!-- 基本信息卡片 -->
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <h3>基本信息</h3>
            </div>
          </template>
          
          <el-descriptions :column="3" border>
            <el-descriptions-item label="出库单号" :span="1">
              {{ stockOut.orderNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="出库类型" :span="1">
              {{ getOrderTypeText(stockOut.orderType) }}
            </el-descriptions-item>
            <el-descriptions-item label="出库日期" :span="1">
              {{ formatDateTime(stockOut.orderDate) }}
            </el-descriptions-item>
            <el-descriptions-item label="仓库" :span="1">
              {{ stockOut.warehouse ? stockOut.warehouse.name : '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态" :span="1">
              <el-tag :type="getStatusType(stockOut.status)">
                {{ getStatusText(stockOut.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="操作人" :span="1">
              {{ stockOut.operator ? stockOut.operator.name : '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :span="1">
              {{ formatDateTime(stockOut.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间" :span="1">
              {{ formatDateTime(stockOut.updatedAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="用途" :span="1" v-if="stockOut.purpose">
              {{ stockOut.purpose }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">
              {{ stockOut.remarks || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 商品明细卡片 -->
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <h3>商品明细</h3>
            </div>
          </template>
          
          <el-table
            :data="stockOut.items || []"
            border
            style="width: 100%"
          >
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column label="商品名称" min-width="200">
              <template #default="scope">
                {{ getProductName(scope.row.productId) }}
              </template>
            </el-table-column>
            <el-table-column label="SKU" width="120">
              <template #default="scope">
                {{ getProductSku(scope.row.productId) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column label="成本价" width="120">
              <template #default="scope">
                {{ formatPrice(scope.row.costPrice) }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120">
              <template #default="scope">
                {{ formatPrice(scope.row.totalPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="batchNumber" label="批次号" width="120" />
            <el-table-column prop="remarks" label="备注" min-width="150" />
          </el-table>
          
          <div class="table-footer">
            <div class="table-summary">
              <span>合计: {{ stockOut.items ? stockOut.items.length : 0 }} 种商品, 总金额: {{ formatPrice(stockOut.totalAmount) }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 操作记录卡片 -->
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <h3>操作记录</h3>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :timestamp="formatDateTime(activity.timestamp)"
              :type="activity.type"
              :color="activity.color"
              :size="activity.size"
              :hollow="activity.hollow"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
        
        <!-- 底部操作按钮 -->
        <div class="detail-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" @click="handlePrint">打印出库单</el-button>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getStockOutOrderById, 
  confirmStockOutOrder, 
  cancelStockOutOrder 
} from '@/api/inventory';
import { formatDateTime, formatPrice } from '@/utils/format';
import permission from '@/directives/permission';

export default {
  name: 'StockOutDetail',
  directives: { permission },
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    // 状态定义
    const loading = ref(false);
    const stockOut = ref(null);
    const products = ref([]);
    
    // 出库单类型映射
    const orderTypes = {
      1: '销售出库',
      2: '报损出库',
      3: '调拨出库',
      4: '其他出库'
    };
    
    // 出库单状态映射
    const orderStatus = {
      0: '草稿',
      1: '已确认',
      2: '已取消'
    };
    
    // 操作记录（模拟数据）
    const activities = reactive([
      {
        content: '创建出库单',
        timestamp: '',
        type: 'primary',
        size: 'normal',
        color: '#0bbd87',
        hollow: false
      },
      {
        content: '更新出库单',
        timestamp: '',
        type: 'warning',
        size: 'normal',
        color: '#e6a23c',
        hollow: false
      },
      {
        content: '确认出库单',
        timestamp: '',
        type: 'success',
        size: 'large',
        color: '#67c23a',
        hollow: false
      }
    ]);
    
    // 加载出库单详情
    const loadStockOutOrder = async () => {
      loading.value = true;
      try {
        const response = await getStockOutOrderById(route.params.id);
        stockOut.value = response.data;
        
        // 更新模拟的操作记录时间
        if (stockOut.value) {
          activities[0].timestamp = stockOut.value.createdAt;
          activities[1].timestamp = stockOut.value.updatedAt;
          
          // 如果已确认，添加确认时间
          if (stockOut.value.status === 1) {
            activities[2].timestamp = stockOut.value.updatedAt;
          } else {
            // 删除确认记录
            activities.pop();
          }
        }
      } catch (error) {
        console.error('Failed to load stock-out order:', error);
        ElMessage.error('获取出库单详情失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 获取状态文本
    const getStatusText = (status) => {
      return orderStatus[status] || '未知状态';
    };
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const map = {
        0: 'info',    // 草稿
        1: 'success', // 已确认
        2: 'danger'   // 已取消
      };
      return map[status] || '';
    };
    
    // 获取状态图标
    const getStatusIcon = (status) => {
      const map = {
        0: 'Edit',    // 草稿
        1: 'Select',  // 已确认
        2: 'Close'    // 已取消
      };
      return map[status] || 'Info';
    };
    
    // 获取状态类
    const getStatusClass = (status) => {
      const map = {
        0: 'status-draft',    // 草稿
        1: 'status-confirmed', // 已确认
        2: 'status-cancelled'  // 已取消
      };
      return map[status] || '';
    };
    
    // 获取出库类型文本
    const getOrderTypeText = (type) => {
      return orderTypes[type] || '未知类型';
    };
    
    // 获取商品名称
    const getProductName = (productId) => {
      const product = products.value.find(p => p.id === productId);
      return product ? product.name : `商品(ID:${productId})`;
    };
    
    // 获取商品SKU
    const getProductSku = (productId) => {
      const product = products.value.find(p => p.id === productId);
      return product ? product.sku : '';
    };
    
    // 编辑出库单
    const handleEdit = () => {
      router.push(`/admin/inventory/stock-out/edit/${stockOut.value.id}`);
    };
    
    // 确认出库单
    const handleConfirm = () => {
      ElMessageBox.confirm('确认该出库单将减少商品库存，是否继续？', '确认出库', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await confirmStockOutOrder(stockOut.value.id);
          ElMessage.success('出库单已确认');
          loadStockOutOrder(); // 重新加载数据
        } catch (error) {
          console.error('Failed to confirm stock-out order:', error);
          ElMessage.error('确认出库单失败: ' + (error.response?.data?.message || '未知错误'));
        }
      }).catch(() => {
        // 用户取消操作
      });
    };
    
    // 作废出库单
    const handleCancel = () => {
      ElMessageBox.confirm('作废出库单后将无法恢复，是否继续？', '作废出库单', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await cancelStockOutOrder(stockOut.value.id);
          ElMessage.success('出库单已作废');
          loadStockOutOrder(); // 重新加载数据
        } catch (error) {
          console.error('Failed to cancel stock-out order:', error);
          ElMessage.error('作废出库单失败');
        }
      }).catch(() => {
        // 用户取消操作
      });
    };
    
    // 打印出库单
    const handlePrint = () => {
      window.print();
    };
    
    // 返回上一页
    const goBack = () => {
      router.push('/admin/inventory/stock-out');
    };
    
    onMounted(() => {
      loadStockOutOrder();
    });
    
    return {
      loading,
      stockOut,
      products,
      activities,
      getStatusText,
      getStatusType,
      getStatusIcon,
      getStatusClass,
      getOrderTypeText,
      getProductName,
      getProductSku,
      handleEdit,
      handleConfirm,
      handleCancel,
      handlePrint,
      goBack,
      formatDateTime,
      formatPrice
    };
  }
};
</script>

<style scoped>
.stock-out-detail {
  padding: 20px;
}

.page-header-title {
  font-size: 18px;
  font-weight: bold;
}

.page-content {
  margin-top: 20px;
}

.status-banner {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  color: white;
}

.status-draft {
  background-color: #909399;
}

.status-confirmed {
  background-color: #67c23a;
}

.status-cancelled {
  background-color: #f56c6c;
}

.status-icon {
  margin-right: 15px;
}

.status-info {
  flex: 1;
}

.status-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.status-info p {
  margin: 0;
  font-size: 14px;
}

.banner-actions {
  display: flex;
  gap: 10px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-footer {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.table-summary {
  font-size: 16px;
  font-weight: bold;
}

.detail-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

@media print {
  .el-page-header,
  .banner-actions,
  .detail-actions {
    display: none;
  }
  
  .page-content {
    margin-top: 0;
  }
}
</style> 